package com.zhuzg.common;

import com.zhuzg.common.config.DataSourceManager;
import com.zhuzg.common.config.DynamicDataSource;
import com.zhuzg.common.domain.TenantDataSource;
import com.zhuzg.common.mapper.DataSourceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取所有的数据源
 */
@Service
public class MultiTenantDataSourceService {

    @Autowired
    private DataSourceManager dataSourceManager;

    @Autowired
    private DynamicDataSource dynamicDataSource;

    @Autowired
    private DataSourceMapper dataSourceMapper;

    @PostConstruct
    public void initialize() {
        // 1、从默认的数据源中查询出所有的租户信息，然后覆盖DynamicDataSource中的targetDataSources属性
        Map<Object, Object> targetDataSources = new HashMap<>();
        //  从数据库当中获取所有的其他数据源
        List<TenantDataSource> tenantDataSources = dataSourceMapper.select();

        for (TenantDataSource tenantDataSource : tenantDataSources) {
            dataSourceManager.addDataSource(tenantDataSource.getTenantId(), tenantDataSource.createDataSource());
        }
        targetDataSources.putAll(dataSourceManager.getAllDataSources());

        dynamicDataSource.setTargetDataSources(targetDataSources);

        // 2、必须执行此操作，才会重新初始化AbstractRoutingDataSource中的resolvedDataSources，也只有这样，动态切换数据源才会起效
        dynamicDataSource.afterPropertiesSet();

    }
}
